package com.hfut.eeg.service;

import com.hfut.eeg.common.util.GetReportTemplate;
import com.hfut.eeg.dao.ReportMapper;
import com.hfut.eeg.dto.ReportInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 进行Report的Service
 */
@Service
public class ReportService {

    @Autowired
    ReportMapper reportMapper;

    @Autowired
    private  GetReportTemplate template;

    /**
    * 插入报告表
    */
    public int insertReport(ReportInfo reportInfo) {
        reportInfo.setReportId(new Date().getTime());
        reportInfo.setTime(new Date());//设定插入报告的时间
        int i = reportMapper.insertReport(reportInfo);
        return i;
    }

    /**
    * 根据病人ID获取报告表
    */
    public ReportInfo getReport(String patientId) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date patientBirth = reportMapper.getPatientBirth(patientId);
        if(patientBirth==null){
            return null;
        }
        Date now=df.parse(df.format(new Date()));
        long daysBetween=(patientBirth.getTime()-now.getTime()+1000000)/(60*60*24*1000);
        int years = (int)daysBetween/365;
        int months = (int)daysBetween%365;
        ArrayList<ReportInfo> reportInfos = reportMapper.getReport(patientId);
        if(reportInfos==null || reportInfos.size()==0){
            return null;
        }
        Date date = reportInfos.get(0).getTime();
        int index = 0;
        for(int i=1;i<reportInfos.size();i++){
            if(reportInfos.get(i).getTime().getTime()>date.getTime()){
                index = i;
            }
        }
        ReportInfo reportInfo = reportInfos.get(index);
        reportInfo.setReportDate(new Date());//获取生成报告时间

        if(years==0)
            return template.getReportTem(false,months,reportInfo.getWaveNum(),reportInfo);
        else
            return template.getReportTem(true,years,reportInfo.getWaveNum(),reportInfo);
    }

    /**
    * 更新报告表
    */
    public int updateReport(ReportInfo info){
        return reportMapper.updateReport(info);
    }


    public int insertReportList(List<ReportInfo> list){
        return reportMapper.insertReportList(list);
    }
}
